package xyz.bernkastel.goods_in_great_demand.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xyz.bernkastel.goods_in_great_demand.dto.GoodsDto;
import xyz.bernkastel.goods_in_great_demand.entity.Goods;
import xyz.bernkastel.goods_in_great_demand.entity.GoodsTag;
import xyz.bernkastel.goods_in_great_demand.mapper.GoodsMapper;
import xyz.bernkastel.goods_in_great_demand.service.GoodsService;
import xyz.bernkastel.goods_in_great_demand.service.GoodsTagService;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {
    @Autowired
    private GoodsTagService goodsTagService;

    /**
     * 新增商品，同时保存对应标签
     *
     * @param goodsDto
     */
    @Override
    @Transactional
    public void saveWithTag(GoodsDto goodsDto) {
        //保存基本数据到goods
        this.save(goodsDto);
        Long goodsId = goodsDto.getId();    //商品id
        List<GoodsTag> tags = goodsDto.getTags();
        tags = tags.stream().map((item) -> {
            item.setGoodsId(goodsId);
            return item;
        }).collect(Collectors.toList());
        //保存标签到goods_tag
        goodsTagService.saveBatch(tags);
    }

    /**
     * 根据id查询商品及其标签
     *
     * @param id
     * @return
     */
    @Override
    public GoodsDto getByIdWithTag(Long id) {
        //从goods查基本信息
        Goods goods = this.getById(id);
        GoodsDto goodsDto = new GoodsDto();
        BeanUtils.copyProperties(goods, goodsDto);
        //从goods_tag查标签
        LambdaQueryWrapper<GoodsTag> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GoodsTag::getGoodsId, goods.getId());
        List<GoodsTag> tags = goodsTagService.list(queryWrapper);
        goodsDto.setTags(tags);

        return goodsDto;
    }

    @Override
    @Transactional
    public void updateWithTag(GoodsDto goodsDto) {
        //更新goods
        this.updateById(goodsDto);

        //先清理当前goods_tag
        LambdaQueryWrapper<GoodsTag> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(GoodsTag::getGoodsId, goodsDto.getId());
        goodsTagService.remove(queryWrapper);

        //再添加
        List<GoodsTag> tags = goodsDto.getTags();
        tags = tags.stream().map((item) -> {
            item.setGoodsId(goodsDto.getId());
            return item;
        }).collect(Collectors.toList());
        goodsTagService.saveBatch(tags);
    }
}
